<template>
  <div class="app-container">
    <el-card :bordered="false">
      <el-form  ref="formValidate" :rules="ruleValidate" :model="formValidate" label-width="130px" >
        <el-row :gutter="24">
          <!-- 商家信息-->
          <el-col v-bind="grid2">
            <el-form-item label="	身份证名称：" prop="realName">
              <el-input v-model="formValidate.realName" :disabled="disabled" placeholder="请输入身份证名称"  />
            </el-form-item>
          </el-col>
          <el-col v-bind="grid2">
            <el-form-item label="身份证证件号：" prop="cardId">
              <el-input v-model="formValidate.cardId" :disabled="disabled" placeholder="身份证证件号"  />
            </el-form-item>
          </el-col>

          <el-col v-bind="grid2">
            <el-form-item label="绑定所属会员：" prop="uid">
              <el-select
                v-model="formValidate.uid"
                filterable
                :disabled="disabled"
                remote
                reserve-keyword
                @change="change"
                placeholder="请输入会员名称"
                :remote-method="remoteMethod"
                :loading="loading">
                <el-option
                  v-for="item in memberList"
                  :key="item.uid"
                  :label="item.nickname"
                  :value="item.uid">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col v-bind="grid2">
            <el-form-item label="绑定所属推荐人：" prop="referrerId">
              <el-select
                v-model="formValidate.referrerId"
                filterable
                :disabled="disabled"
                @change="onChange"

                remote
                reserve-keyword
                placeholder="请输入推荐人名称"
                :remote-method="remoteMethod1"
                :loading="loading">
                <el-option
                  v-for="item in merchantList"
                  :key="item.uid"
                  :label="item.nickname"
                  :value="item.uid">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col v-bind="grid2">
            <el-form-item label="	请选择角色" prop="roleId">
              <el-select v-model="formValidate.roleId" clearable placeholder="请选择">
                <el-option
                  v-for="item in options"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <!-- <el-col v-bind="grid2">
            <el-form-item label="状态" prop="">
              <el-radio v-model="formValidate.isShow" label="1">显示</el-radio>
             <el-radio v-model="formValidate.isShow" label="2">不显示</el-radio>
            </el-form-item>
          </el-col> -->
          <el-col :span="24">
            <el-form-item label="营业执照：" prop="businessLicense">
              <single-pic v-model="formValidate.businessLicense" :disabled="!disabled" type="image" :num="1" :width="150" :height="150" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="身份证正面照:" prop="cardFrontImg">
              <single-pic v-model="formValidate.cardFrontImg " :disabled="!disabled" type="image" :num="1" :width="150" :height="150" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="	身份证反面照：" prop="cardReverseImg">
              <single-pic v-model="formValidate.cardReverseImg" :disabled="!disabled" type="image" :num="4" :width="150" :height="150" />
            </el-form-item>
          </el-col>
        </el-row>


        <el-form-item v-if="!disabled">
          <el-button type="primary" class="submission" @click="handleSubmit('formValidate')">保存</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <period-form ref="form" ></period-form>
  </div>
</template>

<script>
// import { getCates } from '@/api/yxStoreCategory'
import { add, edit, getInfo, isFormatAttr,getMerList } from '@/api/yxStoreMerchant'
import { getCates,getDetailsById ,getYxUser} from '@/api/yxStoreBusiness'
import PeriodForm from './PeriodForm.vue'
import  regionData from '@/utils/city_list.js'
import editor from '../../components/Editor'
import picUpload from '@/components/pic-upload'
import mulpicUpload from '@/components/mul-pic-upload'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import MaterialList from '@/components/material'
import singlePic from '@/components/singlematerial'
import UeditorWrap from 'vue-ueditor-wrap';
export default {
  components: { editor, picUpload, mulpicUpload, Treeselect, MaterialList, UeditorWrap, singlePic,PeriodForm },
  data() {
    return {

      disabled:false,
      props: {
        value: 'n',
        label:'n',
        children:'c',
        multiple:false
      },
      spinShow: false,
      grid2: {
        xl: 10,
        lg: 12,
        md: 12,
        sm: 24,
        xs: 24
      },
      grid3: {
        xl: 18,
        lg: 18,
        md: 20,
        sm: 24,
        xs: 24
      },

      // 规格数据
      formDynamic: {
        attrsName: '',
        attrsVal: ''
      },
      options:[

      ],
      optionsnative_place: regionData,
      formDynamicNameData: [],
      isBtn: false,
      myConfig: {
        autoHeightEnabled: false, // 编辑器不自动被内容撑高
        initialFrameHeight: 500, // 初始容器高度
        initialFrameWidth: '100%', // address
        UEDITOR_HOME_URL: '/UEditor/',
        serverUrl: ''
      },
      columns: [],
      carouselMapArr:[],
      otherQualificationsArr:[],
      formValidate: {

        businessLicense	:'',
        cardFrontImg:'',
        cardId:'',//	身份证证件号		false
        cardReverseImg:'',//	身份证反面照		false
        id:'',//
        realName:'',//	身份证名称
        referrerId:'',//	推荐人id
        remark:'',//	备注
        roleId:'',//	角色id
        uid:'',//

        // state	:'',
      },
      ruleList: [],
      templateList: [],
      createBnt: false,
      showIput: false,
      manyFormValidate: [],
      images: [],
      grid: {
        xl: 8,
        lg: 8,
        md: 12,
        sm: 24,
        xs: 24
      },
      personnelLevel:0,
      loading: false,
      merchantList:[],
      memberList:[],
      treeSelect: [],
      optionsMetaShow: [],
      tableIndex: 0,
      openPeriod:false,
      ruleValidate: {

        realName: [
          { required: true, message: '请输入身份证名称', trigger: 'blur' }
        ],
        uid:[
        { required: true, message: '请选择所属会员', trigger: 'blur' }

        ],
        // cardFrontImg: [
        //   { required: true, message: '请选择身份证正面照', trigger: 'blur' }
        // ],
        cardId: [
          { required: true, message: '请输入身份证证件号', trigger: 'change' }
        ],
        // cardReverseImg: [
        //   { required: true, message: '请选择身份证反面照', trigger: 'blur' }
        // ],
        referrerId: [
          { required: true, message: '请选择推荐人', trigger: 'change' }
        ],
        // businessLicense: [
        //   { required: true, message: '请选择营业执照', trigger: 'blur' }
        // ],
        roleId: [
          { required: true, message: '请选择角色', trigger: 'blur' }
        ],
        uid: [
          { required: true, message: '请选择会员', trigger: 'blur' }
        ],


      },
      attrs: [],
      list: [{
              id:3,
              name:'招商',
              personnelLevel:1,
            },
            {
              id:4,
              name:'经销商',
              personnelLevel:2
            },
            {
              id:5,
              name:'批发商',
              personnelLevel:3

            },
            {
              id:6,
              name:'团购',
              personnelLevel:4

            }]
    }
  },
  watch: {

    'form.sliderImageArr': function(val) {
      if (val) {
        this.form.slider_image = val.join(',')
      }
    }
  },
  mounted () {
    this.dataFilter()
    console.log('this.$route',this.$route.params.id);
    if (this.$route.params.id){
      this.getDetailsById()

    }else{
      this.$refs.form.setWeekTime()
    }
    if(this.$route.name=='businessLook'){
      this.disabled=true
    }else{
      this.disabled=false
    }


  },
  methods: {
    change(e){
      let data=this.memberList.find(item=>item.uid==e)
      if (data.superNickname) {
        this.merchantList=[{
            uid:data.spreadUid,
            nickname:data.superNickname
        }]
        this.formValidate.referrerId=data.spreadUid
        this.options=[]
        this.list.forEach(item => {
          if (item.personnelLevel>=data.superLevel) {
            this.options.push(item)
          }
        });

      }else{
        this.formValidate.referrerId=''
        this.merchantList=[]

      }
      console.log('e',e,data)
    },
    onChange(e){
      let data=this.merchantList.find(item=>item.uid==e)
      this.personnelLevel=data.personnelLevel
      this.options=[]

            this.list.forEach(item => {
          if (item.personnelLevel>=this.personnelLevel) {
            this.options.push(item)
          }
        });
      console.log(e,data)
    },
    synchronization(){
     console.log(this.formValidate.dayTime,this.formValidate.validTime);

       this.formValidate.validTime =this.formValidate.dayTime

    },
    getPoint(){
      window.open('https://lbs.qq.com/getPoint/')
    },
    getDetailsById(){
      let params={}
       params.id=this.$route.params.id
      getDetailsById(params).then(res=>{
        let data=res.data
          this.formValidate=data
          console.log(this.formValidate)
          this.formValidate.address=[data.province,data.city,data.district]
          this.formValidate.latitude=data.latitude+','+data.longitude
          this.carouselMapArr=data.carouselMap ? data.carouselMap.split(",") : []
          this.otherQualificationsArr=data.otherQualifications ? data.otherQualifications.split(",") : []



          this.$refs.form.time.weekTime=weekList
          this.$refs.form.week=1
          console.log('weekList',weekList)

          this.formValidate.validTime=data.validTime?data.validTime.split('-'):["00:00","22:00"]
          this.formValidate.cateId=Number(data.cateId)
          this.formValidate.uid=data.uid+''
          this.merchantList.push({
            nickname: data.nickname,
            uid: data.uid
          })
          this.$forceUpdate()
      })


    },
    dataFilter(){
      getCates().then(res=>{
        this.optionsMetaShow=this.recursion(res.content)

      })

    },
    recursion(arr){
      let content=[]
      arr.forEach(item => {
        let obj={}
        obj.cateName='|-----'+item.cateName
        obj.id=item.id
        content.push(obj)
        if (item.children&&item.children.length>0) {
          item.children.forEach(item1=>{
            let obj1={}
            obj1.cateName='|-----|-----'+item1.cateName
            obj1.id=item1.id
            content.push(obj1)
          })
        }
      });
      return content
    },
    remoteMethod(query) {
      console.log(query)
        if (query !== '') {
          this.loading = true;
          getYxUser({
            nickname: query,
            classifiedQuery:1,
            page:0,
            size:20
          }).then(res => {
            console.log("==============")
            console.log(res)
            this.loading = false;
            this.memberList = res.content
          })
        } else {
          this.memberList = [];
        }
      },
      remoteMethod1(query) {
      console.log(query)
        if (query !== '') {
          this.loading = true;
          getYxUser({
            nickname: query,
            classifiedQuery:2,
            page:0,
            size:20
          }).then(res => {
            console.log("==============")
            console.log(res)
            this.loading = false;
            this.merchantList = res.content
          })
        } else {
          this.merchantList = [];
        }
      },
    confirm () {
      let that = this;
      that.createBnt = true;
      if (that.formValidate.selectRule.trim().length <= 0) {
        return this.$message({
          message:'请选择属性',
          type: 'error'
        });
      }
      that.ruleList.forEach(function (item, index) {
        if (item.ruleName === that.formValidate.selectRule) {
          that.attrs = item.ruleValue;
        }
      });
    },


    // 提交
    handleSubmit (name) {


      this.$refs[name].validate((valid) => {
        if (valid) {
          console.log(this.formValidate)
            if (this.$route.params.id) {
                    edit(this.formValidate).then(async res => {
                      this.$message({
                        message:'操作成功',
                        type: 'success'
                      });
                      setTimeout(() => {
                        this.$router.push({ path: '/shop/business/list' });
                      }, 500);
                    }).catch(res => {
                      this.$message({
                        message:res.message,
                        type: 'error'
                      });
                })
            }else{
              add(this.formValidate).then(async res => {
                this.$message({
                  message:'操作成功',
                  type: 'success'
                });
                setTimeout(() => {
                  this.$router.push({ path: '/shop/business/list' });
                }, 500);
              }).catch(res => {
                this.$message({
                  message:res.message,
                  type: 'error'
                });
              })
            }
        }else{
          this.formValidate.validTime=this.formValidate.validTime.split('-')
        }
      })
    },
    // 表单验证
    validate (prop, status, error) {
      if (status === false) {
        this.$message.warning(error);
      }
    },
    addCustomDialog () {
      window.UE.registerUI('yshop', function (editor, uiName) {
        let dialog = new window.UE.ui.Dialog({
          iframeUrl: '/yshop/materia/index',
          editor: editor,
          name: uiName,
          title: '上传图片',
          cssRules: 'width:1200px;height:500px;padding:20px;'
        });
        this.dialog = dialog;

        var btn = new window.UE.ui.Button({
          name: 'dialog-button',
          title: '上传图片',
          cssRules: `background-image: url(../../../assets/images/icons.png);background-position: -726px -77px;`,
          onclick: function () {
            dialog.render();
            dialog.open();
          }
        });

        return btn;
      }, 37);
    },


    cancel() {
      this.resetForm()
    }
  }
}
</script>

<style scoped lang="stylus">
  .submission
    margin-left 10px;
  .color-list .tip{
    color: #c9c9c9;
  }
  .color-list .color-item{
    height: 30px;
    line-height: 30px;
    padding: 0 10px;
    color:#fff;
    margin-right :10px;
  }
  .color-list .color-item.blue{
    background-color: #1E9FFF;
  }
  .color-list .color-item.yellow{
    background-color: rgb(254, 185, 0);
  }
  .color-list .color-item.green{
    background-color: #009688;
  }
  .columnsBox
    margin-right 10px
  .priceBox
    width 100%
  .rulesBox
    display flex
    flex-wrap: wrap;
  .curs
    cursor pointer
</style>
